package com.wgchao.authodemo.infrastructure.jpa.base.dao;

import com.wgchao.authodemo.domian.entity.base.AgencyDO;
import com.wgchao.authodemo.domian.entity.base.dao.AgencyDao;
import com.wgchao.authodemo.infrastructure.jpa.base.AgencyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName: AgencyDaoImpl
 * @author: wgchao
 * @createTime: 2019/12/10 3:09 PM
 * @Description: TODO
 */
@Component
public class AgencyDaoImpl implements AgencyDao {
    @Autowired
    private AgencyRepository agencyRepository;

    @Override
    public AgencyDO saveOrUpdate(AgencyDO agency) {
        agency = agencyRepository.save(agency);
        return agency;
    }

    @Override
    public void delete(AgencyDO agency) {
        agencyRepository.delete(agency);
    }

    @Override
    public AgencyDO search(Long agencyId) {
        Optional<AgencyDO> agencyOptional = agencyRepository.findById(agencyId);
        if(agencyOptional.isPresent()){
            return agencyOptional.get();
        }
        return null;
    }

    @Override
    public AgencyDO search(String code) {
        AgencyDO agencyDO = agencyRepository.findFirstByCode(code);
        return agencyDO;
    }

    @Override
    public List<AgencyDO> searchChilds(String code) {
        List<AgencyDO> agencyList = agencyRepository.findAllByCodeLikeOrderByCode(code);
        return agencyList;
    }

    @Override
    public String searchMaxChild(String parentCode) {
        String maxCode = agencyRepository.findNextChildCode(parentCode);
        if(StringUtils.isEmpty(maxCode)){
            //新增机构是第一个下级机构
            return parentCode+"0000";
        }
        else {
            //新增机构不是第一个下级机构 +1
            String index = "0000"+(Integer.valueOf(maxCode.substring(maxCode.length() - 4))+1);
            return maxCode.substring(0, maxCode.length()-4)+index.substring(index.length()-4, index.length());
        }
    }
}
